package com.sinodata.bsm.center.web.action.event;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.EventRuleBean;
import com.sinodata.bsm.center.bean.EventRuleBo;
import com.sinodata.bsm.center.bean.ResTypeBean;
import com.sinodata.bsm.center.cache.AttributeCache;
import com.sinodata.bsm.center.cache.DefaultEventExcludeRuleCache;
import com.sinodata.bsm.center.cache.DefaultEventRuleCache;
import com.sinodata.bsm.center.cache.EventRuleCache;
import com.sinodata.bsm.center.cache.EventTypeCache;
import com.sinodata.bsm.center.cache.PropertyCache;
import com.sinodata.bsm.center.cache.PropertyDisplayCache;
import com.sinodata.bsm.center.cache.ResCache;
import com.sinodata.bsm.center.expression.Expressions;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.event.EventRuleService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.EventConstants;
import com.sinodata.bsm.common.utils.CrontabUtil;
import com.sinodata.bsm.common.utils.StringUtil;
import com.sinodata.bsm.common.vo.Attribute;
import com.sinodata.bsm.common.vo.DefaultEventExcludeRule;
import com.sinodata.bsm.common.vo.DefaultEventRule;
import com.sinodata.bsm.common.vo.EventRule;
import com.sinodata.bsm.common.vo.EventType;
import com.sinodata.bsm.common.vo.Property;
import com.sinodata.bsm.common.vo.PropertyDisplay;
import com.sinodata.bsm.common.vo.Res;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-6-18 PM 4:07:58     liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class EventRuleAction extends BaseAction<EventRule> {

    /**
     * 
     */
    private static final long serialVersionUID = 2668812527542248664L;
    @Autowired
    private EventRuleService eventRuleService;
    @Autowired
    private EventTypeCache eventTypeCache;
    @Autowired
    private PropertyCache propertyCache;
    @Autowired
    private AttributeCache attributeCache;
    @Autowired
    private EventRuleCache eventRuleCache;
    @Autowired
    private PropertyDisplayCache propertyDisplayCache;
    @Autowired
    private ResCache resCache;
    @Autowired
    private DefaultEventRuleCache defaultEventRuleCache;
    @Autowired
    private DefaultEventExcludeRuleCache defaultEventExcludeRuleCache;
    private EventRule entity;
    private Long id;
    private final Pattern propPattern = Pattern.compile("(prop\\(\\d+,\\d+[L|l]?\\))");

    private final Pattern tpropPattern = Pattern.compile("(tprop\\(\\d+,\\d+[L|l]?,\\S+\\))");

    private final Pattern attrPattern = Pattern.compile("(attr\\(\\d+,\\d+[L|l]?\\))");

    private final Pattern lastPropPattern = Pattern.compile("(lastPropValue\\(\\d+,\\d+[L|l]?\\))");

    private final Pattern incPattern = Pattern.compile("(inc\\(\\d+,\\d+[L|l]?,\\d+\\))");

    // private final Pattern ipPattern = Pattern.compile("(ip\\(\\d+\\))");

    //private final Pattern resnamePattern = Pattern.compile("(resname\\(\\d+\\))");

    private static final String tpropRegex = "tprop\\((\\d+),(\\d+)[L|l]?,([^\\)]+)\\)";

    /**
     * 跳转至默认表格页面
     * 
     * @return
     */
    public String common() {
        Struts2Utils.getRequest().setAttribute("pId", request.getParameter("pId"));
        Struts2Utils.getRequest().setAttribute("viewId", request.getParameter("viewId"));
        Struts2Utils.getRequest().setAttribute("resId", request.getParameter("id"));
        return "common";
    }

    /**
     * 跳转至应用其他资源页面
     * @return
     */
    public String apply() {
        Struts2Utils.getRequest().setAttribute("resId", request.getParameter("resId"));
        return "apply";
    }

    public String batchApplySave() throws Exception {
        String idsValue = Struts2Utils.getParameter("ids");
        String[] resIds = idsValue.split(",");
        Long[] ids = new Long[resIds.length];
        for (int i = 0; i < resIds.length; i++) {
            ids[i] = Long.parseLong(resIds[i]);
        }
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));

        List<EventRule> fromList = eventRuleCache.getEventRule(resId);
        if (fromList == null || fromList.size() == 0) {
            fromList = new ArrayList(0);
        }
        List<EventRule> list = new ArrayList<EventRule>();
        for (long toResId : ids) {
            //先清空资源对应旧的规则
            eventRuleService.deleteByResId(toResId);
            List<EventRule> listOld = eventRuleCache.getEventRule(toResId);
            for (EventRule eventRule : listOld) {
                EventRuleBean.removeEventRule(eventRule);
            }
            for (EventRule eventRule : fromList) {
                EventRule e = new EventRule();
                e.setId(null);
                e.setResId(toResId);
                e.setDuration(eventRule.getDuration());
                e.setEventTypeId(eventRule.getEventTypeId());
                e.setExpr(changeResId(eventRule.getExpr(), toResId));
                e.setLevel(eventRule.getLevel());
                e.setMsg(changeResId(eventRule.getMsg(), toResId));
                e.setRemarks(eventRule.getRemarks());
                e.setVailTime(eventRule.getVailTime());
                e.setExprIsDefault(eventRule.getExprIsDefault());
                e.setMsgIsDefault(eventRule.getMsgIsDefault());
                e.setConfirmDuration(eventRule.getConfirmDuration());
                e.setFilterDuration(eventRule.getFilterDuration());
                e.setStatus(eventRule.getStatus());
                list.add(e);
            }
        }
        //复制默认事件规则
        List<Long> defaultEventRuleIdFromList = defaultEventExcludeRuleCache.getDefaultEventRuleIdByResId(resId);
        Collections.sort(defaultEventRuleIdFromList);
        for (EventRule eventRule : list) {
            List<Long> defaultEventRuleIdToList = defaultEventExcludeRuleCache.getDefaultEventRuleIdByResId(eventRule.getResId());
            Collections.sort(defaultEventRuleIdToList);
            //from里没有的就删除
            if (defaultEventRuleIdToList != null) {
                for (Long defaultEventRuleId : defaultEventRuleIdToList) {
                    if (Collections.binarySearch(defaultEventRuleIdFromList, defaultEventRuleId) <= -1) {
                        DefaultEventExcludeRule defaultEventExcludeRule = defaultEventExcludeRuleCache.getByResIdDefaultEventRuleId(eventRule.getResId(), defaultEventRuleId);
                        eventRuleService.deleteDefaultEventExcludeRule(defaultEventExcludeRule.getId());
                        defaultEventExcludeRuleCache.remove(defaultEventExcludeRule.getId());
                        EventRuleBean.startDefaultEventRule(defaultEventRuleCache.get(defaultEventRuleId), eventRule.getResId());
                    }
                }
            }
            //to里面没有的就添加
            if (defaultEventRuleIdFromList != null) {
                for (Long defaultEventRuleId : defaultEventRuleIdFromList) {
                    if (Collections.binarySearch(defaultEventRuleIdToList, defaultEventRuleId) <= -1) {
                        DefaultEventExcludeRule defaultEventExcludeRule = new DefaultEventExcludeRule();
                        defaultEventExcludeRule.setResId(eventRule.getResId());
                        defaultEventExcludeRule.setDefaultEventRuleId(defaultEventRuleId);
                        eventRuleService.addDefaultEventExcludeRule(defaultEventExcludeRule);
                        defaultEventExcludeRuleCache.put(defaultEventExcludeRule.getId(), defaultEventExcludeRule);
                        EventRuleBean.stopDefaultEventRule(defaultEventRuleCache.get(defaultEventRuleId), eventRule.getResId());
                    }
                }
            }
        }
        //复制自定义事件规则
        eventRuleService.batchApplySave(list);
        //更新缓存并注册
        for (EventRule eventRule : list) {
            EventRuleBean.addEventRule(eventRule);
        }
        return null;
    }

    private String changeResId(String str, Long resId) {
        List<String> nodes1 = Expressions.parseNodes(attrPattern, str);
        for (int i = 0; i < nodes1.size(); i++) {
            String node = nodes1.get(i);
            String attrId = node.split(",")[1].substring(0, node.split(",")[1].length() - 2);
            String m = "attr(" + resId + "," + attrId + "L)";
            str = StringUtil.replace(str, node, m);
        }
        List<String> nodes2 = Expressions.parseNodes(propPattern, str);
        for (int i = 0; i < nodes2.size(); i++) {
            String node = nodes2.get(i);
            String propId = node.split(",")[1].substring(0, node.split(",")[1].length() - 2);
            String m = "prop(" + resId + "," + propId + "L)";
            str = StringUtil.replace(str, node, m);
        }
        List<String> nodes3 = Expressions.parseNodes(lastPropPattern, str);
        for (int i = 0; i < nodes3.size(); i++) {
            String node = nodes3.get(i);
            String propId = node.split(",")[1].substring(0, node.split(",")[1].length() - 2);
            String m = "lastPropValue(" + resId + "," + propId + "L)";
            str = StringUtil.replace(str, node, m);
        }
        Pattern resPattern = Pattern.compile("(resname\\((\\d+)\\))");
        Matcher matcher = resPattern.matcher(str);
        while (matcher.find()) {
            String str1 = matcher.group(1);
            String str2 = "resname(" + resId + ")";
            str = StringUtil.replace(str, str1, str2);
        }
        Pattern resPattern1 = Pattern.compile("(ip\\((\\d+)\\))");
        Matcher matcher1 = resPattern1.matcher(str);
        while (matcher1.find()) {
            String str1 = matcher1.group(1);
            String str2 = "ip(" + resId + ")";
            str = StringUtil.replace(str, str1, str2);
        }
        return str;
    }

    public String addExpr() throws Exception {
        if (!request.getParameter("eventTypeId").equals("null")) {
            String exprTemple = eventTypeCache.get(Long.valueOf(request.getParameter("eventTypeId"))).getExpr();
            String expr1 = new String(request.getParameter("expr1").getBytes("ISO-8859-1"), "UTF-8");
            expr1 = expr1.replace(" ", "----");
            expr1 = java.net.URLDecoder.decode(expr1, "UTF-8");
            expr1 = expr1.replace("----", "+");
            expr1 = StringUtil.replace(expr1, "$resid", request.getParameter("resId"));
            //非自定义事件类别
            if (exprTemple != null) {
                //默认
                String expr = StringUtil.replace(exprTemple, "$resid", request.getParameter("resId"));
                if (!expr1.equals("")) {
                    if (request.getParameter("exprIsDefault").equals("1")) {
                        String s2 = StringUtil.replace(eventTypeCache.get(Long.valueOf(request.getParameter("eventTypeId"))).getExpr(), "$resid", request.getParameter("resId"));
                        String s1 = expr1;
                        String[] nodes = s2.split("\\$var");
                        for (int i = 0; i < nodes.length; i++) {
                            s1 = s1.replace(nodes[i], "@#@");
                        }
                        String[] values = s1.split("@#@");
                        if (values.length > 1) {
                            for (int i = 1; i < values.length; i++) {
                                s2 = StringUtil.replaceFirst(s2, "$var", "<input type=\"text\" name=\"text1\" id=\"text1\" size=\"5\" value=\"" + values[i] + "\" />");
                            }
                        }
                        expr = exrpFormate(s2);
                    } else {
                        expr = StringUtil.replace(exrpFormate(expr), "$var", "<input type=\"text\" name=\"text1\" id=\"text1\" size=\"5\" />");
                    }
                } else {
                    expr = StringUtil.replace(exrpFormate(expr), "$var", "<input type=\"text\" name=\"text1\" id=\"text1\" size=\"5\" />");
                }
                Struts2Utils.getRequest().setAttribute("expr", expr);
                //自定义
                String expr2 = "";
                if (!expr1.equals("")) {
                    expr2 = expr1;
                } else {
                    expr2 = StringUtil.replace(exprTemple, "$resid", request.getParameter("resId"));
                }
                expr2 = toDefaultExprMsgFormate(expr2);
                expr2 = StringUtil.replace(expr2, "$var", "");
                Struts2Utils.getRequest().setAttribute("expr2", expr2);
                Struts2Utils.getRequest().setAttribute("exprIsDefault", request.getParameter("exprIsDefault"));
                Struts2Utils.getRequest().setAttribute("defineEventType", request.getParameter("defineEventType"));
            } else {//自定义事件类别
                Struts2Utils.getRequest().setAttribute("exprIsDefault", 0);
                Struts2Utils.getRequest().setAttribute("defineEventType", 1);
                if (!expr1.equals("")) {
                    String expr2 = expr1;
                    Struts2Utils.getRequest().setAttribute("expr2", expr2);
                }
            }
            Struts2Utils.getRequest().setAttribute("resId", request.getParameter("resId"));
            Struts2Utils.getRequest().setAttribute("eventTypeId", request.getParameter("eventTypeId"));
            Struts2Utils.getRequest().setAttribute("resName", resCache.get(Long.valueOf(request.getParameter("resId"))).getName());

        }
        return "addexpr";
    }

    public String addExprValue() {
        String expr1 = eventTypeCache.get(Long.valueOf(request.getParameter("eventTypeId"))).getExpr();
        expr1 = StringUtil.replace(expr1, "$resid", request.getParameter("resId"));
        expr1 = exrpFormate(expr1);
        String expr = eventTypeCache.get(Long.valueOf(request.getParameter("eventTypeId"))).getExpr();
        if (request.getParameter("text") != null && !"".equals(request.getParameter("text"))) {
            String[] array = request.getParameter("text").split(",");
            for (String s : array) {
                expr = StringUtil.replaceFirst(expr, "$var", s);
                expr1 = StringUtil.replaceFirst(expr1, "$var", s);
            }
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("expr", expr);
        map.put("expr1", expr1);
        map.put("array", request.getParameter("text"));
        Struts2Utils.renderJson(map);
        return null;
    }

    public String addMsg() throws Exception {
        if (!request.getParameter("eventTypeId").equals("null")) {
            String msg1 = new String(request.getParameter("msg1").getBytes("ISO-8859-1"), "UTF-8");
            msg1 = msg1.replace(" ", "----");
            msg1 = java.net.URLDecoder.decode(msg1, "UTF-8");
            msg1 = msg1.replace("----", "+");
            String msgTemple = eventTypeCache.get(Long.valueOf(request.getParameter("eventTypeId"))).getMsg();
            //非自定义事件类别
            if (msgTemple != null) {
                //默认
                String msg = StringUtil.replace(msgTemple, "$resid", request.getParameter("resId"));
                Struts2Utils.getRequest().setAttribute("msg1", msg);
                msg = msgFormate(msg, Long.valueOf(request.getParameter("resId")));
                Struts2Utils.getRequest().setAttribute("msg", msg);
                //自定义
                String msg2 = StringUtil.replace(msgTemple, "$resid", request.getParameter("resId"));
                if (!msg1.equals("") && request.getParameter("msgIsDefault").equals("0")) {
                    msg2 = msg1;
                }
                msg2 = toDefaultExprMsgFormate(msg2);
                Struts2Utils.getRequest().setAttribute("msg2", msg2);
                Struts2Utils.getRequest().setAttribute("msgIsDefault", request.getParameter("msgIsDefault"));
                Struts2Utils.getRequest().setAttribute("defineEventType", request.getParameter("defineEventType"));
            } else {//自定义事件类别
                msg1 = toDefaultExprMsgFormate(msg1);
                Struts2Utils.getRequest().setAttribute("msg1", msg1);
                Struts2Utils.getRequest().setAttribute("msg2", msg1);
                Struts2Utils.getRequest().setAttribute("msgIsDefault", 0);
                Struts2Utils.getRequest().setAttribute("defineEventType", 1);
            }
            Struts2Utils.getRequest().setAttribute("resId", request.getParameter("resId"));
            Struts2Utils.getRequest().setAttribute("resName", resCache.get(Long.valueOf(request.getParameter("resId"))).getName());
        }
        return "addmsg";
    }

    public String viewMsg() throws Exception {
        String msg = new String(request.getParameter("msg").getBytes("ISO-8859-1"), "UTF-8");
        msg = msg.replace(" ", "----");
        msg = java.net.URLDecoder.decode(msg, "UTF-8");
        msg = msg.replace("----", "+");
        msg = replaceEquals(msg);
        msg = defaultExprMsgFormate(msg);
        try {
            if (!msg.contains("tprop")) {
                Object o = Expressions.test(msg);
                msg = o.toString();
            }
        } catch (Exception e) {
            Struts2Utils.getRequest().setAttribute("msg", "预览消息失败,请确认消息设置是否正确");
            return "viewmsg";
        }
        msg = msg.replace(" ", "&nbsp; ");
        Struts2Utils.getRequest().setAttribute("msg", msg);
        return "viewmsg";
    }

    public String havePropIdbyPropName() throws Exception {
        String msg = new String(request.getParameter("propRuleSelect").getBytes("ISO-8859-1"), "UTF-8");
        msg = msg.replace(" ", "----");
        msg = java.net.URLDecoder.decode(msg, "UTF-8");
        msg = msg.replace("----", "+");
        Res res = resCache.get(Long.valueOf(msg.substring(msg.indexOf("{") + 1, msg.indexOf(":"))));
        ResTypeBean resTypeBean = ResTypeBean.get(res.getResTypeId());
        List<Property> list = propertyCache.getByResId(res.getId());
        List<Property> listProperty = new ArrayList<Property>();
        if (list != null) {
            listProperty.addAll(list);
        }
        if (resTypeBean.properties() != null) {
            listProperty.addAll(resTypeBean.properties());
        }

        for (Property property : listProperty) {
            if (property.getName().equals(msg.substring(msg.indexOf(":") + 1, msg.indexOf("}")))) {
                renderText(property.getId().toString());
                return null;
            }
        }
        return null;
    }

    public String addMsgValue() throws Exception {
        String msg = new String(request.getParameter("text").getBytes("ISO-8859-1"), "UTF-8");
        msg = msg.replace(" ", "----");
        msg = java.net.URLDecoder.decode(msg, "UTF-8");
        msg = msg.replace("----", "+");
        msg = defaultExprMsgFormate(msg);
        Map<String, String> map = new HashMap<String, String>();
        map.put("msg", msg);
        Struts2Utils.renderJson(map);
        return null;
    }

    //指标下拉框
    public String propertyList() {
        if (request.getParameter("resId") != null && !request.getParameter("resId").equals("")) {
            Long resId = Long.valueOf(request.getParameter("resId"));
            Res res = resCache.get(resId);
            //默认的指标
            ResTypeBean resTypeBean = ResTypeBean.get(res.getResTypeId());
            //自定义的指标
            List<Property> list = propertyCache.getByResId(res.getId());
            //自定义sql或者脚本中的指标
            List<PropertyDisplay> myDefineList = propertyDisplayCache.getPropertysByResId(resId);
            List<Property> listProperty = new ArrayList<Property>();
            if (list != null) {
                listProperty.addAll(list);
            }
            if (myDefineList != null) {
                for (PropertyDisplay propertyDisplay : myDefineList) {
                    Property p = new Property();
                    p.setId(propertyDisplay.getPropId());
                    p.setName(propertyDisplay.getDisplayName());
                    p.setDataTypeId(propertyCache.get(propertyDisplay.getPropId()).getDataTypeId());
                    listProperty.add(p);
                }
            }
            if (resTypeBean.properties() != null) {
                for (Property p : resTypeBean.properties()) {
                    if (!p.getResType().equals(1205040500000l) && !p.getResType().equals(1205040600000l)) {
                        listProperty.add(p);
                    }
                }
            }

            List<Map<String, String>> listResult = new ArrayList<Map<String, String>>();
            if (listProperty != null) {
                Map<String, String> map1 = new HashMap<String, String>();
                map1.put("id", "");
                map1.put("name", "选择指标");
                listResult.add(map1);
                for (Property property : listProperty) {
                    if (property.getDataTypeId() == 4) {
                        for (String colName : property.getFormat().split("[|]")) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("id", "$TP{" + request.getParameter("resId") + ":" + property.getName() + ":" + colName + "}");
                            map.put("name", property.getName() + ":" + colName);
                            listResult.add(map);
                        }
                    } else {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("id", "$P{" + request.getParameter("resId") + ":" + property.getName() + "}");
                        String name = property.getName();
                        if (property.getDataUnit() != null) {
                            name = name + "(" + property.getDataUnit() + ")";
                        }
                        map.put("name", name);
                        listResult.add(map);
                    }
                }
            }
            Struts2Utils.renderJson(listResult);
        }
        return null;
    }

    //属性下拉框
    public String attributeList() {
        if (request.getParameter("resId") != null && !request.getParameter("resId").equals("")) {
            Long resId = Long.valueOf(request.getParameter("resId"));
            Res res = resCache.get(resId);
            ResTypeBean resTypeBean = ResTypeBean.get(res.getResTypeId());
            List<Attribute> list = attributeCache.getByResId(resId);
            List<Attribute> listAttribute = new ArrayList<Attribute>();
            if (list != null) {
                listAttribute.addAll(list);
            }
            if (resTypeBean.attributes() != null) {
                listAttribute.addAll(resTypeBean.attributes());
            }

            List<Map<String, String>> listResult = new ArrayList<Map<String, String>>();
            if (listAttribute != null) {
                Map<String, String> map1 = new HashMap<String, String>();
                map1.put("id", "");
                map1.put("name", "选择属性");
                listResult.add(map1);
                for (Attribute attribute : listAttribute) {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("id", "$A{" + request.getParameter("resId") + ":" + attribute.getName() + "}");
                    String name = attribute.getName();
                    map.put("name", name);
                    listResult.add(map);
                }
            }
            Struts2Utils.renderJson(listResult);
        }
        return null;
    }

    //转向新增页面
    public String add() {
        Struts2Utils.getRequest().setAttribute("resId", request.getParameter("resId"));
        Res res = resCache.get(Long.valueOf(request.getParameter("resId")));
        if (res == null) {
            return "add";
        }
        ResTypeBean resTypeBean = ResTypeBean.get(res.getResTypeId());
        List<EventType> listEventType = resTypeBean.eventType();
        //自定义事件类别
        List<EventType> list = eventTypeCache.findByResId(res.getId());
        List<EventType> listResult = new ArrayList<EventType>();
        if (listEventType != null) {
            listResult.addAll(listEventType);
        }
        if (list != null) {
            listResult.addAll(list);
        }
        Struts2Utils.getRequest().setAttribute("eventTypeList", listResult);
        if (listResult != null && listResult.size() != 0) {
            EventType eventType = listResult.get(0);
            String msgTemple = eventType.getMsg();
            if (msgTemple != null) {
                String msg = StringUtil.replace(msgTemple, "$resid", request.getParameter("resId"));
                Struts2Utils.getRequest().setAttribute("msg1", msg);
                msg = msgFormate(msg, Long.valueOf(request.getParameter("resId")));
                Struts2Utils.getRequest().setAttribute("msg", msg);
                Struts2Utils.getRequest().setAttribute("objectExpr", eventType.getObjectExpr() == null ? "" : eventType.getObjectExpr());
            } else {
                Struts2Utils.getRequest().setAttribute("msg1", "");
                Struts2Utils.getRequest().setAttribute("msg", "");
            }
            Struts2Utils.getRequest().setAttribute("recoverable", eventType.getRecoverable());
        }

        Struts2Utils.getRequest().setAttribute("pId", request.getParameter("pId"));
        Struts2Utils.getRequest().setAttribute("viewId", request.getParameter("viewId"));
        return "add";
    }

    public String haveMsgByEventTypeId() {
        Map<String, String> map = new HashMap<String, String>();
        EventType eventType = eventTypeCache.get(Long.valueOf(request.getParameter("eventTypeId")));
        String msgTemple = eventType.getMsg();
        if (msgTemple != null) {
            String msg = StringUtil.replace(msgTemple, "$resid", request.getParameter("resId"));
            map.put("msg1", msg);
            msg = msgFormate(msg, Long.valueOf(request.getParameter("resId")));
            map.put("msg", msg);
            map.put("objectExpr", eventType.getObjectExpr() == null ? "" : eventType.getObjectExpr());
        } else {
            map.put("msg1", "");
            map.put("msg", "");
        }
        map.put("recoverable", eventType.getRecoverable() + "");
        Struts2Utils.renderJson(map);
        return null;
    }

    //将msg 相应的Id换成名字
    private String msgFormate(String msg, Long resId) {
        while (msg.indexOf(".equals(") != -1) {
            msg = replaceEquals(msg);
        }
        List<String> nodes1 = Expressions.parseNodes(attrPattern, msg);
        for (int i = 0; i < nodes1.size(); i++) {
            String node = nodes1.get(i);
            String attrId = node.split(",")[1].substring(0, node.split(",")[1].length() - 2);
            Attribute a = attributeCache.get(Long.valueOf(attrId));
            String m = "attr(" + resId + "," + a.getName() + ")";
            msg = StringUtil.replace(msg, node, m);
        }
        List<String> nodes2 = Expressions.parseNodes(propPattern, msg);
        for (int i = 0; i < nodes2.size(); i++) {
            String node = nodes2.get(i);
            //解析prop
            String propId = node.split(",")[1].substring(0, node.split(",")[1].length() - 2);
            Property p = propertyCache.get(Long.valueOf(propId));
            String m = "prop(" + resId + "," + p.getName() + ")";
            msg = StringUtil.replace(msg, node, m);
        }
        List<String> nodes4 = Expressions.parseNodes(tpropPattern, msg);
        for (int i = 0; i < nodes4.size(); i++) {
            String node = nodes4.get(i);
            //解析prop
            String propId = node.split(",")[1].substring(0, node.split(",")[1].length() - 1);
            Property p = propertyCache.get(Long.valueOf(propId));
            String m = "tprop(" + resId + "," + p.getName() + "," + node.substring(node.lastIndexOf(",") + 1, node.length() - 1) + ")";
            msg = StringUtil.replace(msg, node, m);
        }
        List<String> nodes3 = Expressions.parseNodes(incPattern, msg);
        for (int i = 0; i < nodes3.size(); i++) {
            String node = nodes3.get(i);
            String propId = node.split(",")[1].substring(0, node.split(",")[1].length() - 1);
            Property property = propertyCache.get(Long.valueOf(propId));
            StringBuffer sbuffer = new StringBuffer();
            sbuffer.append(property.getName());
            int second = Integer.parseInt(node.split(",")[2].substring(0, node.split(",")[2].indexOf(")")));
            int minute = 0;
            //下面词条去掉request 因为这一部分要与指标一块使用 而指标是与部属环境相关的
            if (second % 60 == 0) {
                minute = second / 60;
                sbuffer.append(minute + "分钟");
            } else {
                minute = second / 60;
                second = second - minute * 60;
                if (minute > 0) {
                    sbuffer.append(minute + "分钟" + second + "秒");
                } else {
                    sbuffer.append(second + "秒");
                }
            }
            msg = StringUtil.replace(msg, node, sbuffer.toString());
        }
        //回显resName
        Pattern resPattern = Pattern.compile("(resname\\((\\d+)\\))");
        Matcher matcher = resPattern.matcher(msg);
        while (matcher.find()) {
            String str = matcher.group(1);
            String resId1 = matcher.group(2);
            String resName = resCache.get(Long.valueOf(resId1)).getName();
            if (resName.indexOf("(") != -1 || resName.indexOf(")") != -1) {
                resName = StringUtil.replace(resName, "(", "");
                resName = StringUtil.replace(resName, ")", "");
            }
            String descript = "resname(" + resId + ":" + resName + ")";
            msg = StringUtil.replace(msg, str, descript);
        }
        //回显ip
        Pattern resPattern1 = Pattern.compile("(ip\\((\\d+)\\))");
        Matcher matcher1 = resPattern1.matcher(msg);
        while (matcher1.find()) {
            String str = matcher1.group(1);
            String resId1 = matcher1.group(2);
            String resName = resCache.get(Long.valueOf(resId1)).getName();
            if (resName.indexOf("(") != -1 || resName.indexOf(")") != -1) {
                resName = StringUtil.replace(resName, "(", "");
                resName = StringUtil.replace(resName, ")", "");
            }
            String descript = "ip(" + resId + ":" + resName + ")";
            msg = StringUtil.replace(msg, str, descript);
        }
        return msg;
    }

    @Override
    public EventRule getModel() {
        return entity;
    }

    @Override
    public String list() throws Exception {
        String resId = request.getParameter("resId");
        List<EventRuleBo> list = eventRuleService.findByResId(Long.valueOf(resId));
        JSONObject json = new JSONObject();
        json.element("iTotalRecords", list.size());
        json.element("iTotalDisplayRecords", list.size());
        JSONArray array = new JSONArray();
        //权限控制
        boolean sysManager = UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER);
        //默认规则
        List<DefaultEventRule> defaultEventRuleList = eventRuleService.getDefaultEventRuleByResId(Long.valueOf(resId));
        Collections.sort(defaultEventRuleList, new Comparator<DefaultEventRule>() {
            @Override
            public int compare(DefaultEventRule obj2, DefaultEventRule obj1) {
                return obj1.getId().intValue() - obj2.getId().intValue();
            }
        });
        List<Long> scope = defaultEventExcludeRuleCache.getDefaultEventRuleIdByResId(Long.valueOf(resId));
        Collections.sort(scope);
        if (defaultEventRuleList != null && defaultEventRuleList.size() != 0) {
            for (DefaultEventRule defaultEventRule : defaultEventRuleList) {
                JSONObject obj = new JSONObject();
                String expr = StringUtil.replace(defaultEventRule.getExpr(), "$resid", resId);
                obj.element("expr", exrpFormate(expr));
                obj.element("op", "<div style='width: 50px'>&nbsp;&nbsp;&nbsp;<a href='javascript:" + (Collections.binarySearch(scope, defaultEventRule.getId()) > -1 ? "start" : "stop") + "(" + defaultEventRule.getId() + ",0," + resId + ");'><img src='../style/default/bsm/images/" + (Collections.binarySearch(scope, defaultEventRule.getId()) > -1 ? "start.gif' title='启用'" : "stop.gif' title='禁用'") + "></a><div>");
                obj.element("resName", "<a href='javascript:view(" + defaultEventRule.getId() + ",0);'>" + resCache.get(Long.valueOf(resId)).getName() + "</a>");
                obj.element("id", defaultEventRule.getId());
                obj.element("eventTypeName", eventTypeCache.get(defaultEventRule.getEventTypeId()).getName());
                obj.element("levelName", "<img src='../style/default/images/" + defaultEventRule.getLevel() + ".gif' title='" + EventConstants.getLevelDesc(defaultEventRule.getLevel()) + "' />" + EventConstants.getLevelDesc(defaultEventRule.getLevel()));
                obj.element("duration", defaultEventRule.getDuration() == null ? "0" : defaultEventRule.getDuration());
                obj.element("vailTime", "全天");
                obj.element("status", Collections.binarySearch(scope, defaultEventRule.getId()) > -1 ? "禁用" : "启用");
                obj.element("statusIndex", Collections.binarySearch(scope, defaultEventRule.getId()) > -1 ? "0" : "1");
                array.add(obj);
            }
        }
        //自定义规则
        for (EventRuleBo eventRuleBean : list) {
            JSONObject obj = new JSONObject();
            try {
                obj.element("expr", exrpFormate(eventRuleBean.eventRule().getExpr()));
                if (sysManager) {
                    obj.element("op", "<div style='width: 100px'>&nbsp;&nbsp;&nbsp;<a href='javascript:" + (eventRuleBean.eventRule().getStatus() == 1 ? "stop" : "start") + "(" + eventRuleBean.eventRule().getId() + ",1," + resId + ");'><img src='../style/default/bsm/images/" + (eventRuleBean.eventRule().getStatus() == 1 ? "stop.gif' title='禁用'" : "start.gif' title='启用'") + "></a>&nbsp;<a href='javascript:update(" + eventRuleBean.eventRule().getId() + ");'><img src='../style/default/bsm/images/edit.gif' title='修改'></a>&nbsp;<a href='javascript:del(" + eventRuleBean.eventRule().getId() + ");'><img src='../style/default/bsm/images/delete.gif' title='删除'></a><div>");
                }
                obj.element("resName", "<a href='javascript:view(" + eventRuleBean.eventRule().getId() + ",1);'>" + eventRuleBean.getResName() + "</a>");
            } catch (Exception e) {
                //规则表达式中的属性或者指标不存在
                obj.element("expr", "此条规则已作废");
                if (sysManager) {
                    obj.element("op", "<div style='width: 60px'>&nbsp;&nbsp;&nbsp;<a href='javascript:del(" + eventRuleBean.eventRule().getId() + ");'><img src='../style/default/bsm/images/delete.gif' title='删除'></a><div>");
                }
                obj.element("resName", eventRuleBean.getResName());
            }
            obj.element("id", eventRuleBean.eventRule().getId());
            obj.element("eventTypeName", eventRuleBean.getEventTypeName());
            obj.element("levelName", "<img src='../style/default/images/" + eventRuleBean.eventRule().getLevel() + ".gif' title='" + EventConstants.getLevelDesc(eventRuleBean.eventRule().getLevel()) + "' />" + EventConstants.getLevelDesc(eventRuleBean.eventRule().getLevel()));
            obj.element("duration", eventRuleBean.eventRule().getDuration() == null ? "" : eventRuleBean.eventRule().getDuration());
            obj.element("vailTime", eventRuleBean.eventRule().getVailTime().equals("0") ? "全天" : CrontabUtil.CronParser(eventRuleBean.eventRule().getVailTime().split("@")[0]) + "," + CrontabUtil.parseSimple(Integer.valueOf(eventRuleBean.eventRule().getVailTime().split("@")[1])));
            obj.element("status", eventRuleBean.eventRule().getStatus() == 0 ? "禁用" : "启用");
            obj.element("statusIndex", eventRuleBean.eventRule().getStatus() == 0 ? "0" : "1");
            array.add(obj);
        }
        json.element("aaData", array);
        renderText(json.toString());
        return null;
    }

    /**
     * 转化成自定义的格式
     * @param expr
     * @return
     */
    private String toDefaultExprMsgFormate(String expr) {
        List<String> nodes1 = Expressions.parseNodes(attrPattern, expr);
        for (int i = 0; i < nodes1.size(); i++) {
            String node = nodes1.get(i);
            String attrId = node.split(",")[1].substring(0, node.split(",")[1].length() - 2);
            Attribute a = attributeCache.get(Long.valueOf(attrId));
            String m = "$A{" + node.split(",")[0].substring(node.split(",")[0].lastIndexOf("(") + 1, node.split(",")[0].length()) + ":" + a.getName() + "}";
            expr = StringUtil.replace(expr, node, m);
        }
        List<String> nodes2 = Expressions.parseNodes(propPattern, expr);
        for (int i = 0; i < nodes2.size(); i++) {
            String node = nodes2.get(i);
            //解析prop
            String propId = node.split(",")[1].substring(0, node.split(",")[1].length() - 2);
            Property p = propertyCache.get(Long.valueOf(propId));
            String m = "$P{" + node.split(",")[0].substring(node.split(",")[0].lastIndexOf("(") + 1, node.split(",")[0].length()) + ":" + p.getName() + "}";
            expr = StringUtil.replace(expr, node, m);
        }

        //表格类型
        Map<String, String> map = StringUtil.getAllByRegex(expr, tpropRegex);
        if (map.size() > 1) {
            Map<String, String> values = new HashMap<String, String>();
            for (String st : map.keySet()) {
                if (st.equals("sum")) {
                    continue;
                }
                values.put(st, transExpr(map.get(st), tpropRegex));
            }
            String expression = map.get("sum");
            for (String key : values.keySet()) {
                expression = expression.replace(key, values.get(key));
            }
            expr = expression;
        }

        return expr;
    }

    //转向修改页面
    @Override
    public String input() throws Exception {
        ResTypeBean resTypeBean = ResTypeBean.get(resCache.get(Long.valueOf(request.getParameter("resId"))).getResTypeId());
        List<EventType> listEventType = resTypeBean.eventType();
        //自定义事件类别
        List<EventType> list = eventTypeCache.findByResId(Long.valueOf(request.getParameter("resId")));
        List<EventType> listResult = new ArrayList<EventType>();
        if (listEventType != null) {
            listResult.addAll(listEventType);
        }
        if (list != null) {
            listResult.addAll(list);
        }
        EventRule eventRule = eventRuleService.get(Long.valueOf(request.getParameter("id")));
        Struts2Utils.getRequest().setAttribute("resId", request.getParameter("resId"));
        String expr = StringUtil.replace(eventRule.getExpr(), "$resid", String.valueOf(eventRule.getResId()));
        if (eventRule.getExprIsDefault().equals(0)) {
            expr = toDefaultExprMsgFormate(expr);
            Struts2Utils.getRequest().setAttribute("expr1", expr);
            Struts2Utils.getRequest().setAttribute("expr", expr);
        } else {
            Struts2Utils.getRequest().setAttribute("expr1", expr);
            Struts2Utils.getRequest().setAttribute("expr", exrpFormate(expr));
        }
        String msg = StringUtil.replace(eventRule.getMsg(), "$resid", String.valueOf(eventRule.getResId()));
        if (eventRule.getMsgIsDefault().equals(0)) {
            msg = toDefaultExprMsgFormate(msg);
            Struts2Utils.getRequest().setAttribute("msg", msg);
        } else {
            Struts2Utils.getRequest().setAttribute("msg", msgFormate(msg, eventRule.getResId()));
        }
        if (eventRule.getFilterDuration() == null) {
            eventRule.setFilterDuration(0);
        }
        if (eventRule.getConfirmDuration() == null) {
            eventRule.setConfirmDuration(0);
        }
        Struts2Utils.getRequest().setAttribute("eventTypeList", listResult);
        Struts2Utils.getRequest().setAttribute("eventRule", eventRule);
        Struts2Utils.getRequest().setAttribute("recoverable", eventTypeCache.get(eventRule.getEventTypeId()).getRecoverable());
        //判断是否为自定义事件类别
        if (eventTypeCache.get(eventRule.getEventTypeId()).getResTypeId() == null) {
            Struts2Utils.getRequest().setAttribute("defineEventType", 1);
        } else {
            Struts2Utils.getRequest().setAttribute("defineEventType", 0);
        }

        Struts2Utils.getRequest().setAttribute("pId", request.getParameter("pId"));
        Struts2Utils.getRequest().setAttribute("viewId", request.getParameter("viewId"));
        return "update";
    }

    //将expr 相应的Id换成名字
    private String exrpFormate(String expr) {
        while (expr.indexOf(".equals(") != -1) {
            expr = replaceEquals(expr);
        }
        List<String> nodes1 = Expressions.parseNodes(attrPattern, expr);
        for (int i = 0; i < nodes1.size(); i++) {
            String node = nodes1.get(i);
            String m = explainAttrParameter(node);
            expr = StringUtil.replace(expr, node, m);
        }
        List<String> nodes2 = Expressions.parseNodes(propPattern, expr);
        for (int i = 0; i < nodes2.size(); i++) {
            String node = nodes2.get(i);
            String m = explainPropParameter(node);
            expr = StringUtil.replace(expr, node, m);
        }
        List<String> nodes3 = Expressions.parseNodes(incPattern, expr);
        for (int i = 0; i < nodes3.size(); i++) {
            String node = nodes3.get(i);
            String m = explainIncParameter(node);
            expr = StringUtil.replace(expr, node, m);
        }
        List<String> nodes4 = Expressions.parseNodes(Pattern.compile("(lastPropValue\\(\\d+,\\d+[L|l]?\\))"), expr);
        for (int i = 0; i < nodes4.size(); i++) {
            String node = nodes4.get(i);
            String m = explainLastPropParameter(node);
            expr = StringUtil.replace(expr, node, m);
        }
        Map<String, String> map = StringUtil.getAllByRegex(expr, tpropRegex);
        if (map.size() > 1) {
            expr = explainTPropParameter(map);
        }

        Pattern resPattern = Pattern.compile("(resname\\((\\d+)\\))");
        Matcher matcher = resPattern.matcher(expr);
        while (matcher.find()) {
            String str = matcher.group(1);
            String resId1 = matcher.group(2);
            String resName = resCache.get(Long.valueOf(resId1)).getName();
            if (resName.indexOf("(") != -1 || resName.indexOf(")") != -1) {
                resName = StringUtil.replace(resName, "(", "");
                resName = StringUtil.replace(resName, ")", "");
            }
            String descript = "resname(" + resId1 + ":" + resName + ")";
            expr = StringUtil.replace(expr, str, descript);
        }
        Pattern resPattern1 = Pattern.compile("(ip\\((\\d+)\\))");
        Matcher matcher1 = resPattern1.matcher(expr);
        while (matcher1.find()) {
            String str = matcher1.group(1);
            String resId1 = matcher1.group(2);
            String resName = resCache.get(Long.valueOf(resId1)).getName();
            if (resName.indexOf("(") != -1 || resName.indexOf(")") != -1) {
                resName = StringUtil.replace(resName, "(", "");
                resName = StringUtil.replace(resName, ")", "");
            }
            String descript = "ip(" + resId1 + ":" + resName + ")";
            expr = StringUtil.replace(expr, str, descript);
        }
        return expr;
    }

    //inc转换成name
    private String explainIncParameter(String temp) {
        StringBuffer sbuffer = new StringBuffer();
        String[] a = StringUtil.convertStringToStringArray(temp, ",");
        Long propId = Long.valueOf(a[1].substring(0, a[1].lastIndexOf("L")));
        Property property = propertyCache.get(propId);
        sbuffer.append(property.getName());
        int second = Integer.parseInt(a[2].substring(0, a[2].indexOf(")")));
        int minute = 0;
        //下面词条去掉request 因为这一部分要与指标一块使用 而指标是与部属环境相关的
        if (second % 60 == 0) {
            minute = second / 60;
            sbuffer.append(minute + "分钟");
        } else {
            minute = second / 60;
            second = second - minute * 60;
            if (minute > 0) {
                sbuffer.append(minute + "分钟" + second + "秒");
            } else {
                sbuffer.append(second + "秒");
            }
        }
        return sbuffer.toString();
    }

    //attr转换name
    private String explainAttrParameter(String temp) {
        String attrId = temp.substring(temp.indexOf(",") + 1, temp.length() - 2);
        Attribute attribute = attributeCache.get(Long.valueOf(attrId));
        String unit = (attribute.getDataUnit() == null || attribute.getDataUnit().equals("")) ? "" : "(" + attribute.getDataUnit() + ")";
        return attribute.getName() + unit;
    }

    //prop转换name
    private String explainPropParameter(String temp) {
        StringBuffer sb = new StringBuffer();
        String propId = temp.substring(temp.indexOf(",") + 1, temp.length() - 2);
        String resId = temp.substring(5, temp.indexOf(","));
        Property property = propertyCache.get(Long.parseLong(propId));
        boolean flag = true;
        if (propertyDisplayCache.getPropertysByResId(Long.valueOf(resId)) != null) {
            for (PropertyDisplay propertyDisplay : propertyDisplayCache.getPropertysByResId(Long.valueOf(resId))) {
                if (propertyDisplay.getPropId().equals(Long.valueOf(propId))) {
                    sb.append(propertyDisplay.getDisplayName());
                    flag = false;
                    break;
                }
            }
        }
        if (flag) {
            sb.append(property.getName());
        }
        String unit = (property.getDataUnit() == null || property.getDataUnit().equals("")) ? "" : "(" + property.getDataUnit() + ")";
        sb.append(unit);
        return sb.toString();
    }

    //tprop转换name
    //    private String explainTPropParameter(String temp) {
    //        StringBuffer sb = new StringBuffer();
    //        String propId = temp.substring(temp.indexOf(",") + 1, temp.lastIndexOf(",") - 1);
    //        Property property = propertyCache.get(Long.parseLong(propId));
    //        sb.append(property.getName() + ":" + temp.substring(temp.lastIndexOf(",") + 1, temp.length() - 1));
    //        String unit = (property.getDataUnit() == null || property.getDataUnit().equals("")) ? "" : "(" + property.getDataUnit() + ")";
    //        sb.append(unit);
    //        return sb.toString();
    //    }
    private String explainTPropParameter(Map<String, String> map) {
        String exp = map.get("sum");
        Map<String, String> value = new HashMap<String, String>();
        for (String key : map.keySet()) {
            if (!"sum".equals(key)) {
                value.put(key, explainSingleTPropParameter(map.get(key), tpropRegex));
            }
        }
        for (String key : value.keySet()) {
            exp = exp.replace(key, value.get(key));
        }
        return exp;
    }

    //Lastprop转换name
    private String explainLastPropParameter(String temp) {
        StringBuffer sb = new StringBuffer();
        String propId = temp.substring(temp.indexOf(",") + 1, temp.length() - 2);
        Property property = propertyCache.get(Long.parseLong(propId));
        sb.append("上次" + property.getName());
        String unit = (property.getDataUnit() == null || property.getDataUnit().equals("")) ? "" : "(" + property.getDataUnit() + ")";
        sb.append(unit);
        return sb.toString();
    }

    //转换.equals
    private static String replaceEquals(String str) {
        int index = str.indexOf(".equals(");
        if (index == -1) {
            return str;
        }
        String str1 = str.substring(0, index);
        String str2 = str.substring(index + 8);
        index = -1;
        int s = 0;
        for (int i = 0; i < str2.length(); i++) {
            char ch = str2.charAt(i);
            if (ch == '(') {
                s++;
            } else if (ch == ')') {
                if (s > 0) {
                    s--;
                } else {
                    index = i;
                    break;
                }
            }
        }
        if (index == -1) {
            // 异常
        }
        String str3 = str2.substring(0, index);

        String str4 = "";
        if (str2.length() > index) {
            str4 = str2.substring(index + 1);
        }
        return str1 + "==" + str3 + str4;
    }

    //预览
    public String view() throws Exception {
        if (request.getParameter("flag").equals("1")) {
            EventRule eventRule = eventRuleService.get(id);
            EventRule e = new EventRule();
            e.setId(eventRule.getId());
            e.setResId(eventRule.getResId());
            e.setDuration(eventRule.getDuration());
            e.setEventTypeId(eventRule.getEventTypeId());
            e.setExpr(eventRule.getExpr());
            e.setLevel(eventRule.getLevel());
            e.setMsg(eventRule.getMsg());
            e.setRemarks(eventRule.getRemarks());
            e.setVailTime(eventRule.getVailTime());
            e.setExprIsDefault(eventRule.getExprIsDefault());
            e.setMsgIsDefault(eventRule.getMsgIsDefault());
            e.setConfirmDuration(eventRule.getConfirmDuration());
            e.setFilterDuration(eventRule.getFilterDuration());
            String expr = StringUtil.replace(e.getExpr(), "$resid", String.valueOf(e.getResId()));
            e.setExpr(exrpFormate(expr));
            String msg = StringUtil.replace(e.getMsg(), "$resid", String.valueOf(e.getResId()));
            e.setMsg(msgFormate(msg, e.getResId()));
            if (e.getFilterDuration() == null) {
                e.setFilterDuration(0);
            }
            if (e.getConfirmDuration() == null) {
                e.setConfirmDuration(0);
            }

            Struts2Utils.getRequest().setAttribute("eventRule", e);
            Struts2Utils.getRequest().setAttribute("filterDuration", CrontabUtil.parseSimple(e.getFilterDuration()));
            Struts2Utils.getRequest().setAttribute("confirmDuration", CrontabUtil.parseSimple(e.getConfirmDuration()));
            Struts2Utils.getRequest().setAttribute("recoverable", eventTypeCache.get(e.getEventTypeId()).getRecoverable());
            Struts2Utils.getRequest().setAttribute("eventTypeName", eventTypeCache.get(e.getEventTypeId()).getName());
            Struts2Utils.getRequest().setAttribute("vailTime", e.getVailTime().equals("0") ? "全天" : CrontabUtil.CronParser(e.getVailTime().split("@")[0]) + "开始,持续" + CrontabUtil.parseSimple(Integer.valueOf(e.getVailTime().split("@")[1])));
        } else {
            DefaultEventRule defaultEventRule = defaultEventRuleCache.get(id);
            EventRule e = new EventRule();
            e.setId(defaultEventRule.getId());
            e.setDuration(defaultEventRule.getDuration());
            e.setEventTypeId(defaultEventRule.getEventTypeId());
            e.setExpr(defaultEventRule.getExpr());
            e.setLevel(defaultEventRule.getLevel());
            e.setMsg(defaultEventRule.getMsg());
            e.setRemarks(defaultEventRule.getRemarks());
            e.setVailTime(defaultEventRule.getVailTime());
            e.setConfirmDuration(defaultEventRule.getConfirmDuration());
            e.setFilterDuration(defaultEventRule.getFilterDuration());
            String expr = StringUtil.replace(e.getExpr(), "$resid", request.getParameter("resId"));
            e.setExpr(exrpFormate(expr));
            String msg = StringUtil.replace(e.getMsg(), "$resid", request.getParameter("resId"));
            e.setMsg(msgFormate(msg, Long.valueOf(request.getParameter("resId"))));
            if (e.getFilterDuration() == null) {
                e.setFilterDuration(0);
            }
            if (e.getConfirmDuration() == null) {
                e.setConfirmDuration(0);
            }

            Struts2Utils.getRequest().setAttribute("eventRule", e);
            Struts2Utils.getRequest().setAttribute("recoverable", "1");
            Struts2Utils.getRequest().setAttribute("eventTypeName", eventTypeCache.get(e.getEventTypeId()).getName());
            Struts2Utils.getRequest().setAttribute("vailTime", "全天");
        }
        return "view";
    }

    /**
     * 将自定义的事件规则转换数据库存放的格式
     * @param expr
     * @return
     */
    private String defaultExprMsgFormate(String expr) {
        //解析prop
        Pattern compilePattern = Pattern.compile("(\\$P\\{(\\d+):([^\\}]+)\\})");
        Matcher matcher = compilePattern.matcher(expr);
        while (matcher.find()) {
            String str = matcher.group(1);
            String resId = matcher.group(2);
            String propName = matcher.group(3).trim();
            Long propId = -1l;
            Res res = resCache.get(Long.valueOf(resId));
            ResTypeBean resTypeBean = ResTypeBean.get(res.getResTypeId());
            List<Property> list = propertyCache.getByResId(Long.valueOf(resId));
            //自定义sql或者脚本中的指标
            List<PropertyDisplay> myDefineList = propertyDisplayCache.getPropertysByResId(Long.valueOf(resId));
            List<Property> listProperty = new ArrayList<Property>();
            if (list != null) {
                listProperty.addAll(list);
            }
            if (myDefineList != null) {
                for (PropertyDisplay propertyDisplay : myDefineList) {
                    Property p = new Property();
                    p.setId(propertyDisplay.getPropId());
                    p.setName(propertyDisplay.getDisplayName());
                    p.setDataTypeId(propertyCache.get(propertyDisplay.getPropId()).getDataTypeId());
                    listProperty.add(p);
                }
            }
            if (resTypeBean.properties() != null) {
                listProperty.addAll(resTypeBean.properties());
            }

            for (Property p : listProperty) {
                if (p.getName().equals(propName)) {
                    propId = p.getId();
                    break;
                }
            }
            String newStr = "prop(" + resId + "," + propId + "L)";
            expr = expr.replace(str, newStr);
        }
        //解析attr
        Pattern compilePattern1 = Pattern.compile("(\\$A\\{(\\d+):([^\\}]+)\\})");
        Matcher matcher1 = compilePattern1.matcher(expr);
        while (matcher1.find()) {
            String str = matcher1.group(1);
            String resId = matcher1.group(2);
            String attrName = matcher1.group(3).trim();
            Long attrId = -1l;
            Res res1 = resCache.get(Long.valueOf(resId));
            ResTypeBean resTypeBean1 = ResTypeBean.get(res1.getResTypeId());
            List<Attribute> list1 = attributeCache.getByResId(Long.valueOf(resId));
            List<Attribute> listAttribute = new ArrayList<Attribute>();
            if (list1 != null) {
                listAttribute.addAll(list1);
            }
            if (resTypeBean1.attributes() != null) {
                listAttribute.addAll(resTypeBean1.attributes());
            }

            for (Attribute a : listAttribute) {
                if (a.getName().equals(attrName)) {
                    attrId = a.getId();
                }
            }
            String newStr = "attr(" + resId + "," + attrId + "L)";
            expr = expr.replace(str, newStr);
        }
        //解析ResIp
        Pattern resIpPattern = Pattern.compile("(ip\\((\\d+):([^\\)]+)\\))");
        Matcher matcher2 = resIpPattern.matcher(expr);
        while (matcher2.find()) {
            String str = matcher2.group(1);
            String resId = matcher2.group(2);
            String newStr = "ip(" + resId + ")";
            expr = StringUtil.replace(expr, str, newStr);
        }
        //解析resName
        Pattern resNamePattern = Pattern.compile("(resname\\((\\d+):([^\\)]+)\\))");
        Matcher matcher3 = resNamePattern.matcher(expr);
        while (matcher3.find()) {
            String str = matcher3.group(1);
            String resId = matcher3.group(2);
            String newStr = "resname(" + resId + ")";
            expr = StringUtil.replace(expr, str, newStr);
        }
        //解析tprop
        Pattern compilePattern4 = Pattern.compile("(\\$TP\\{(\\d+):([^\\}]+):([^\\}]+)\\})");
        Matcher matcher4 = compilePattern4.matcher(expr);
        while (matcher4.find()) {
            String str = matcher4.group(1);
            String resId = matcher4.group(2);
            String propName = matcher4.group(3).trim();
            String colName = matcher4.group(4).trim();
            Long propId = -1l;
            Res res = resCache.get(Long.valueOf(resId));
            ResTypeBean resTypeBean = ResTypeBean.get(res.getResTypeId());
            List<Property> list = propertyCache.getByResId(Long.valueOf(resId));
            List<Property> listProperty = new ArrayList<Property>();
            if (list != null) {
                listProperty.addAll(list);
            }
            if (resTypeBean.properties() != null) {
                listProperty.addAll(resTypeBean.properties());
            }

            for (Property p : listProperty) {
                if (p.getName().equals(propName)) {
                    propId = p.getId();
                    break;
                }
            }
            String newStr = "tprop(" + resId + "," + propId + "L," + colName + ")";
            expr = expr.replace(str, newStr);
        }
        return expr;
    }

    @Override
    public String save() throws Exception {
        //TODO 修改时也不能改出相同的规则，判断应该考虑有效时间段内不重复即可
        //解析expr
        String expr = entity.getExpr();
        if (expr == null || expr.equals("")) {
            String expr1 = request.getParameter("expr1");
            entity.setExpr(defaultExprMsgFormate(expr1));
        } else {
            expr = StringUtil.replace(expr, "$resid", String.valueOf(entity.getResId()));
            entity.setExpr(expr);
        }

        //自动确认规则  过滤规则
        if (entity.getConfirmDuration() == null || entity.getConfirmDuration() == 0) {
            entity.setConfirmDuration(null);
        }
        if (eventTypeCache.get(entity.getEventTypeId()).getRecoverable() == EventConstants.TYPE_UNRECOVERABLE) {
            if (entity.getFilterDuration() == null || entity.getFilterDuration() == 0) {
                entity.setFilterDuration(null);
            }
            if (entity.getKeyWord() == null || "".equals(entity.getKeyWord())) {
                entity.setKeyWord(null);
            }
        } else {
            entity.setFilterDuration(null);
            entity.setKeyWord(null);
        }
        //先停用默认规则
        List<DefaultEventRule> defaultEventRuleList = eventRuleService.getDefaultEventRuleByResId(entity.getResId());
        if (defaultEventRuleList != null) {
            for (DefaultEventRule defaultEventRule : defaultEventRuleList) {
                if (defaultEventRule.getEventTypeId().equals(entity.getEventTypeId()) && defaultEventRule.getLevel().equals(entity.getLevel()) && entity.getStatus().equals(1)) {
                    DefaultEventExcludeRule defaultEventExcludeRule = defaultEventExcludeRuleCache.getByResIdDefaultEventRuleId(entity.getResId(), defaultEventRule.getId());
                    if (defaultEventExcludeRule == null) {
                        DefaultEventExcludeRule defaultEventExcludeRule1 = new DefaultEventExcludeRule();
                        defaultEventExcludeRule1.setResId(entity.getResId());
                        defaultEventExcludeRule1.setDefaultEventRuleId(defaultEventRule.getId());
                        eventRuleService.addDefaultEventExcludeRule(defaultEventExcludeRule1);
                        defaultEventExcludeRuleCache.put(defaultEventExcludeRule1.getId(), defaultEventExcludeRule1);
                        EventRuleBean.stopDefaultEventRule(defaultEventRule, entity.getResId());
                    }
                }
            }
        }
        //end
        if (entity.getId() != null) {//修改
            if (eventRuleCache.get(entity.getId()) != null) {
                eventRuleService.update(entity);
                //调用EventRuleBean修改事件规则，先删除再增加，同时更新缓存和注册事件规则
                EventRuleBean.removeEventRule(entity);
                EventRuleBean.addEventRule(entity);
            } else {
                renderText("false");
                return null;
            }
        } else {//新增
            eventRuleService.add(entity);
            //调用EventRuleBean增加事件规则，增加缓存同时注册事件规则
            EventRuleBean.addEventRule(entity);
        }
        renderText("true");
        return null;
    }

    public String stop() {
        Long id = Long.valueOf(request.getParameter("id"));
        Long resId = Long.valueOf(request.getParameter("resId"));
        String flag = request.getParameter("flag");
        //默认
        if (flag.equals("0")) {
            DefaultEventExcludeRule defaultEventExcludeRule = new DefaultEventExcludeRule();
            defaultEventExcludeRule.setResId(resId);
            defaultEventExcludeRule.setDefaultEventRuleId(id);
            eventRuleService.addDefaultEventExcludeRule(defaultEventExcludeRule);
            defaultEventExcludeRuleCache.put(defaultEventExcludeRule.getId(), defaultEventExcludeRule);
            EventRuleBean.stopDefaultEventRule(defaultEventRuleCache.get(id), resId);
        } else {
            //停用自定义规则
            EventRule eventRule = eventRuleCache.get(id);
            eventRule.setStatus(0);
            eventRuleService.update(eventRule);
            EventRuleBean.stopEventRule(eventRule);
        }
        return null;
    }

    public String start() {
        Long id = Long.valueOf(request.getParameter("id"));
        Long resId = Long.valueOf(request.getParameter("resId"));
        String flag = request.getParameter("flag");
        //默认
        if (flag.equals("0")) {
            DefaultEventExcludeRule defaultEventExcludeRule = defaultEventExcludeRuleCache.getByResIdDefaultEventRuleId(resId, id);
            DefaultEventRule defaultEventRule = defaultEventRuleCache.get(defaultEventExcludeRule.getDefaultEventRuleId());
            //判断是否有已启动的自定义事件规则  事件类别+事件级别
            for (EventRule eventRule : eventRuleCache.getEventRule(resId)) {
                if (eventRule.getEventTypeId().equals(defaultEventRule.getEventTypeId()) && eventRule.getLevel().equals(defaultEventRule.getLevel()) && eventRule.getStatus().equals(1)) {
                    eventRule.setStatus(0);
                    eventRuleService.update(eventRule);
                    EventRuleBean.stopEventRule(eventRule);
                }
            }
            eventRuleService.deleteDefaultEventExcludeRule(defaultEventExcludeRule.getId());
            defaultEventExcludeRuleCache.remove(defaultEventExcludeRule.getId());
            EventRuleBean.startDefaultEventRule(defaultEventRule, resId);
            renderText("true");
        } else {
            EventRule eventRule = eventRuleCache.get(id);
            //判断是否有事件类别+事件级别相同的默认事件规则，有责停用默认规则
            List<DefaultEventRule> defaultEventRuleList = eventRuleService.getDefaultEventRuleByResId(resId);
            if (defaultEventRuleList != null) {
                for (DefaultEventRule defaultEventRule : defaultEventRuleList) {
                    if (defaultEventRule.getEventTypeId().equals(eventRule.getEventTypeId()) && defaultEventRule.getLevel().equals(eventRule.getLevel())) {
                        DefaultEventExcludeRule defaultEventExcludeRule = defaultEventExcludeRuleCache.getByResIdDefaultEventRuleId(resId, defaultEventRule.getId());
                        if (defaultEventExcludeRule == null) {
                            DefaultEventExcludeRule defaultEventExcludeRule1 = new DefaultEventExcludeRule();
                            defaultEventExcludeRule1.setResId(resId);
                            defaultEventExcludeRule1.setDefaultEventRuleId(defaultEventRule.getId());
                            eventRuleService.addDefaultEventExcludeRule(defaultEventExcludeRule1);
                            defaultEventExcludeRuleCache.put(defaultEventExcludeRule1.getId(), defaultEventExcludeRule1);
                            EventRuleBean.stopDefaultEventRule(defaultEventRule, resId);
                        }
                    }
                }
            }
            //启用自定义规则
            eventRule.setStatus(1);
            eventRuleService.update(eventRule);
            EventRuleBean.startEventRule(eventRule);
        }
        return null;
    }

    @Override
    public String delete() throws Exception {
        if (eventRuleCache.get(id) != null) {
            //先删除自定义规则
            eventRuleService.delete(id);

            //再启用 因为此条规则 引起停用的默认规则
            EventRule eventRule2 = eventRuleCache.get(id);
            List<DefaultEventRule> list = eventRuleService.getDefaultEventRuleByResId(eventRule2.getResId());
            if (list != null) {
                for (DefaultEventRule defaultEventRule : list) {
                    if (eventRule2.getEventTypeId().equals(defaultEventRule.getEventTypeId()) && eventRule2.getLevel().equals(defaultEventRule.getLevel())) {
                        DefaultEventExcludeRule defaultEventExcludeRule = defaultEventExcludeRuleCache.getByResIdDefaultEventRuleId(eventRule2.getResId(), defaultEventRule.getId());
                        if (defaultEventExcludeRule != null) {
                            //是否还存在自定义事件规则  事件级别和类别  不存在则启用默认事件规则
                            boolean isHave = false;
                            for (EventRule eventRule1 : eventRuleCache.getEventRule(eventRule2.getResId())) {
                                if (!eventRule1.getId().equals(eventRule2.getId()) && eventRule1.getEventTypeId().equals(eventRule2.getEventTypeId()) && eventRule1.getLevel().equals(eventRule2.getLevel()) && eventRule1.getStatus() == 1) {
                                    isHave = true;
                                    break;
                                }
                            }
                            if (!isHave) {
                                eventRuleService.deleteDefaultEventExcludeRule(defaultEventExcludeRule.getId());
                                defaultEventExcludeRuleCache.remove(defaultEventExcludeRule.getId());
                                EventRuleBean.startDefaultEventRule(defaultEventRule, eventRule2.getResId());
                            }
                        }
                    }
                }
            }
            EventRuleBean.removeEventRule(eventRuleCache.get(id));
            renderText("true");
        } else {
            renderText("false");
        }
        return null;
    }

    public String checkDeleted() {
        JSONObject ob = new JSONObject();
        if (eventRuleCache.get(id) == null) {
            ob.element("flag", false);
        } else {
            ob.element("flag", true);
        }
        Struts2Utils.renderJson(ob.toString());
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            entity = eventRuleService.get(id);
            if (entity == null) {
                entity = new EventRule();
            }
        } else {
            entity = new EventRule();
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String validateExpress() throws Exception {
        String express = new String(request.getParameter("express").getBytes("ISO-8859-1"), "UTF-8");
        express = express.replace(" ", "----");
        express = java.net.URLDecoder.decode(express, "UTF-8");
        express = express.replace("----", "+");
        //解析equal
        express = replaceEquals(express);
        express = defaultExprMsgFormate(express);
        try {
            if (!express.contains("tprop")) {
                Expressions.test(express);
            }
        } catch (Exception ex) {
            logger.error("Failed to validateExpress,express=" + express, ex);
            renderText("false");
            return null;
        }
        renderText("true");
        return null;
    }

    public String validateMsg() throws Exception {
        String msg = new String(request.getParameter("msg").getBytes("ISO-8859-1"), "UTF-8");
        msg = msg.replace(" ", "----");
        msg = java.net.URLDecoder.decode(msg, "UTF-8");
        msg = msg.replace("----", "+");
        msg = replaceEquals(msg);
        msg = defaultExprMsgFormate(msg);
        try {
            if (!msg.contains("tprop")) {
                Expressions.test(msg);
            }
        } catch (Exception ex) {
            logger.error("Failed to validateMsg,msg=" + msg, ex);
            renderText("false");
            return null;
        }
        renderText("true");
        return null;
    }

    /**
     * 
     * 该方法是将形如：tprop(25625,120201110000003L,状态)
     * 的字符串转换成：$TP{25625:无效对象列表:状态}
     * @param expr
     * @param regex
     *           tprop\\((\\d+),(\\d+)[L|l]?,([^\\)]+)\\)
     * @return
     */
    private String transExpr(String expr, String regex) {
        Pattern expPattern = Pattern.compile(regex);
        Matcher matcher = expPattern.matcher(expr);
        StringBuffer buffer = new StringBuffer("$TP{");
        if (matcher.find()) {
            Property p = propertyCache.get(Long.valueOf(matcher.group(2)));
            buffer.append(matcher.group(1));
            buffer.append(":");
            buffer.append(p.getName());
            buffer.append(":");
            buffer.append(matcher.group(3));
            buffer.append("}");
        }
        String newExpr = buffer.toString();
        return newExpr;
    }

    /**
     * 将形如：tprop(25625,120201110000003L,状态)的转换成 无效对象列表:状态
     * @param expr
     * 
     * @param regex
     *          tprop\\((\\d+),(\\d+)[L|l]?,([^\\)]+)\\)
     * @return
     */
    private String explainSingleTPropParameter(String expr, String regex) {
        Pattern expPattern = Pattern.compile(regex);
        Matcher matcher = expPattern.matcher(expr);
        StringBuffer buffer = new StringBuffer();
        if (matcher.find()) {
            Property p = propertyCache.get(Long.valueOf(matcher.group(2)));
            buffer.append(p.getName());
            buffer.append(":");
            buffer.append(matcher.group(3));
        }
        String newExpr = buffer.toString();
        return newExpr;
    }
}
